package com.study.common.BaseDao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Date;
import java.util.List;


/**
 * @Create by ldr.
 * @create 2018-08-28 9:43
 * @Description：
 */
public class BaseDaoImpl implements BaseDao {

    @Autowired
    private SessionFactory sessionFactory; // 从容器中注入session工厂

    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }


    @Override
    public void add(Object obj) {
        Session s = getSession();
        s.save(obj);
    }

    @Override
    public void delete(Object obj) {
        Session s = getSession();
        s.delete(obj);
    }

    @Override
    public void update(Object obj) {
        Session s = getSession();
        s.update(obj);
    }

    @Override
    public Object findById(Class clazz,Serializable id) {
        Session s = getSession();
        return s.get(clazz, id);
    }

    @Override
    public void deleteById(Class clazz, Serializable id) {
        Object obj = findById(clazz, id);
        Session s = getSession();
        s.delete(obj);
    }

    @Override
    public Object queryUniqueByHql(String hql, List paramList) {
        Session s=getSession();
        Query q=s.createQuery(hql);
        for(int i=0;i<paramList.size();i++){
            Object paramObj=paramList.get(i);
            if(paramObj instanceof Date){
                q.setTimestamp(i, (Date)paramObj);
            }else{
                q.setParameter(i, paramObj);
            }
        }
        Object result=q.uniqueResult();
        //声明式事务不需要手动给关闭Session
        //s.close();
        return result;
    }


}
